package com.demo.study.proxy;

import com.demo.study.proxy.impl.UserService;
import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ServiceLoader;

/**
 * @author Baymax
 * @since 2021/10/10
 */
public class TestClient {
    @Test
    public void test3() {
        ServiceLoader<IUserService> userServices = ServiceLoader.load(IUserService.class);
        for (IUserService userService : userServices) {
            userService.add();
            System.out.println(userService.query());
        }
    }

    @Test
    public void test2() {
        ProxyHandler<IUserService> proxyHandler = new ProxyHandler<>(new UserService());
        IUserService userService = proxyHandler.getProxy();
        userService.add();
    }

    @Test
    public void test1() {
        IUserService userService = new UserService();
        userService = (IUserService) Proxy.newProxyInstance(TestClient.class.getClassLoader(),
            new Class[]{IUserService.class}, new UserServiceProxy(userService));
        userService.add();
    }
}

class UserServiceProxy implements InvocationHandler {
    private IUserService userService;

    public UserServiceProxy(IUserService userService) {
        this.userService = userService;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(method.getName());
        return method.invoke(userService, args);
    }

    private void before(String name) {
        System.out.println("[INFO]方法:[" + name + "]被调用了");
    }
}
